package cn.legend.travel.tour.team.alipay.controller;


import cn.legend.travel.tour.team.alipay.pojo.param.PayParam;
import cn.legend.travel.tour.team.service.IOrderService;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "9. 模拟支付")
@RestController
@RequestMapping("/alipay")
public class PayController {
    @Autowired
    private IOrderService orderService;

    /**
     * APP ID，请在支付宝沙箱应用（https://open.alipay.com/develop/sandbox/app）中查找正确的值
     */
    private static final String APP_ID = "9021000128612787";
    /**
     * 应用私钥，请在支付宝沙箱应用（https://open.alipay.com/develop/sandbox/app）中查找正确的值
     */
    private static final String PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCKgdFcKsT4htCU5qSZxj5lp/Pcg6Tvl7r6mxuxM+i+nTynm3BNcHiO5RWs/7/jI/HYmOlodAOmtDrjoNBFMJvTJGin+oEC7l8t6zV/SREPafTkoVoEkBUQD/cDYy+K3dL2838NOyKjRQ2OFin7FG7ZJr0Tjb8ZesEfV5SuJDWMWo4iNb4wdeg1qH8Ex/lvk99KCGjSoQovzKa4+sqMFTGAhYKSqFKKwK7hX6jfe1o5tr4HTcX5ihqU1uhprYKwqrxc87UCaNzVHT1nXa11XtIMtayghvIQyJEJs6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HD6XFyFEXkKTLtmzX5dRmuSZs6kddtqWdCgQKBgQDl7OLM/IWteq+MLDo+pXxEETCUinqtX3tyLO0cx421F1lay0Qz/n2WaUuI6+YfabOCaIZ2tTZAvjoKzZCJnA59ndfR5TCDUzLHwECkwISZJpo0FgdcKhwYGfo/zsQPtjxBvtAXvlMSJK+aLOlI5NxHPRYEzV7aUePH7XslgVJHDA==";
    /**
     * 支付宝公钥，请在支付宝沙箱应用（https://open.alipay.com/develop/sandbox/app）中查找正确的值
     */
    private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA48T88XGrFrnJyxovNLqczQ7T/4dOSQbDgwrg5tCIx/puW2YdCMPBCdJZhUB5Dod8nROe9+F/pc0XFbMPAWFR9RWsUUPnfKw0y9LazddMflM2pHi+bPTg8fRNkGeLFlwvu9in5M7OXKKehMrFhHRMHstPTZIGIb89YY/wp6oFnAelqdL4ccUzYl/GywYoETUkiWn+g8LGF9nubIXjrVw7NcgwWZU2c6qR1yh+EKiP7ISo0aXX6ld0DGsGcaGHDcVuztX585k2FYauHgnIm3nYq4RLl3ZiUT8n+pcEBRZFbTZiXb23uv8y/XIzmRvm6Isc1TlmeeK4LyvdglvoF99GsQIDAQAB";
    /**
     * 通知网址，用于处理支付宝完成支付处理后，你的应用中进行下一步处理的请求地址
     */
    private static final String NOTIFY_URL = "http://8m6np8.natappfree.cc/alipay/notify";
    /**
     * 返回网址，用于支付宝完成支付处理后，重定向到某个位置
     */
    private static final String RETURN_URL = "http://8m6np8.natappfree.cc/alipay/finish";
    /**
     * 【固定】支付宝网关
     */
    private static final String ALIPAY_GATEWAY = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    /**
     * 【固定】加密算法
     */
    private static final String ENCRYPTION_ALGORITHM = "RSA2";
    /**
     * 【固定】字符编码
     */
    private static final String CHARSET = "UTF-8";
    /**
     * 【固定】数据格式
     */
    private static final String DATA_FORMAT = "json";

    // 此方法用于接收客户端发起的支付请求，并响应支付表单页面到客户端
    // 网页客户端应该通过window.open直接向此处发起请求，则响应的支付表单会直接显示在window.open打开的窗口中
    @ApiOperation("支付宝沙箱支付")
    @ApiOperationSupport(order = 100)
    @GetMapping("/pay")
    public String pay(PayParam payParam, @ApiIgnore HttpServletResponse response) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(
                ALIPAY_GATEWAY, APP_ID, PRIVATE_KEY, DATA_FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, ENCRYPTION_ALGORITHM);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(NOTIFY_URL);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(RETURN_URL);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", payParam.getOutTradeNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", payParam.getTotalAmount());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", payParam.getSubject());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        /******可选参数******/
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse alipayTradePagePayResponse = alipayClient.pageExecute(request);
        if (alipayTradePagePayResponse.isSuccess()) {
            System.out.println("调用成功，将在浏览器中打开支付宝【沙箱】支付页");
            String responseBody = alipayTradePagePayResponse.getBody();
            System.out.println(responseBody);
            return responseBody;
        } else {
            return "交易失败，调用支付宝远程接口失败，请返回订单页查看订单状态，或重新支付！";
        }
    }

    // 接收支付宝发送的通知（支付结果）
    // 注意：必须是POST请求
    @ApiIgnore
    @PostMapping("/notify")
    public String payNotify(@ApiIgnore HttpServletRequest request) throws Throwable {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, ALIPAY_PUBLIC_KEY, CHARSET); // 验证签名
        // 支付宝验签
        if (checkSignature) {
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家支付宝ID: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            // 你应该在此处补充支付成功后续的代码，例如修改订单状态等
            // 0-待支付,1-已支付,2-待点评,3-审核退款中,4-已完成 调用Service方法修改订单状态
            // 完成
            return "支付完成，商家将尽快发货";
        } else {
            return "支付失败，请返回订单页查看订单状态，或重新支付！";
        }
    }

    // 接收处理支付宝的跳转（支付完成后自动重定向到此处）
    @ApiIgnore
    @GetMapping("/finish")
    public String finish(HttpServletResponse response) throws IOException {
        response.sendRedirect("http://176.223.7.121:10086");
        return "支付完成，请返回订单页查看订单状态！";
    }

}
